package com.cloudkeeper.leasing.identity.controller.impl;

import com.cloudkeeper.leasing.base.model.Result;
import com.cloudkeeper.leasing.identity.controller.VillageCadresAddTemporaryController;
import com.cloudkeeper.leasing.identity.domain.SysDistrict;
import com.cloudkeeper.leasing.identity.domain.VillageCadres;
import com.cloudkeeper.leasing.identity.domain.VillageCadresAddTemporary;
import com.cloudkeeper.leasing.identity.dto.villagecadresaddtemporary.VillageCadresAddTemporaryDTO;
import com.cloudkeeper.leasing.identity.dto.villagecadresaddtemporary.VillageCadresAddTemporarySearchable;
import com.cloudkeeper.leasing.identity.service.SysDistrictService;
import com.cloudkeeper.leasing.identity.service.VillageCadresAddTemporaryService;
import com.cloudkeeper.leasing.identity.service.VillageCadresService;
import com.cloudkeeper.leasing.identity.vo.StatisticsStringVO;
import com.cloudkeeper.leasing.identity.vo.VillageCadresAddTemporaryVO;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 村干部临时表 controller
 * @author asher
 */
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class VillageCadresAddTemporaryControllerImpl implements VillageCadresAddTemporaryController {

    /** 村干部临时表 service */
    private final VillageCadresAddTemporaryService villageCadresAddTemporaryService;

    private final VillageCadresService villageCadresService;

    private final SysDistrictService sysDistrictService;

    @Override
    public Result<VillageCadresAddTemporaryVO> findOne(@ApiParam(value = "村干部临时表id", required = true) @PathVariable String id) {
        Optional<VillageCadresAddTemporary> villageCadresAddTemporaryOptional = villageCadresAddTemporaryService.findOptionalById(id);
        return villageCadresAddTemporaryOptional.map(villageCadresAddTemporary -> Result.of(villageCadresAddTemporary.convert(VillageCadresAddTemporaryVO.class))).orElseGet(Result::ofNotFound);
    }

    @Override
    public Result<VillageCadresAddTemporaryVO> add(@ApiParam(value = "村干部临时表 DTO", required = true) @RequestBody @Validated VillageCadresAddTemporaryDTO villageCadresAddTemporaryDTO) {
        VillageCadresAddTemporary villageCadresAddTemporary = villageCadresAddTemporaryService.save(villageCadresAddTemporaryDTO.convert(VillageCadresAddTemporary.class));
        return Result.ofAddSuccess(villageCadresAddTemporary.convert(VillageCadresAddTemporaryVO.class));
    }

    @Override
    public Result hasFull(@PathVariable String districtId) {
        String sql = "select districtId as name ,(cast (count(1) as VARCHAR)) as val from village_cadres where cadresType = 'IN_SECRETARY' and cadresPost != 'OUT_SECRETARY' and hasRetire = 0 and districtId = "+districtId+" group by districtId";
        List<StatisticsStringVO> list = villageCadresService.findAllBySql(StatisticsStringVO.class,sql);
        SysDistrict sysDistrict = sysDistrictService.findByDistrictId(districtId);
        Map<String,Boolean> map = new HashMap<>();
        if (CollectionUtils.isEmpty(list)){
            map.put("res",true);
            return Result.of(map);
        }
        if (sysDistrict.getCardesNumer() == null){
            map.put("res",false);
            return Result.of(map);
        }
        if (Integer.valueOf(list.get(0).getVal()) >= sysDistrict.getCardesNumer()){
            map.put("res",false);
            return Result.of(map);
        }
        map.put("res",true);
        return Result.of(map);
    }

    @Override
    public Result<VillageCadresAddTemporaryVO> update(@ApiParam(value = "村干部临时表id", required = true) @PathVariable String id,
        @ApiParam(value = "村干部临时表 DTO", required = true) @RequestBody @Validated VillageCadresAddTemporaryDTO villageCadresAddTemporaryDTO) {
        Optional<VillageCadresAddTemporary> villageCadresAddTemporaryOptional = villageCadresAddTemporaryService.findOptionalById(id);

        if (!villageCadresAddTemporaryOptional.isPresent()) {
            return Result.ofLost();
        }
        VillageCadresAddTemporary villageCadresAddTemporary = villageCadresAddTemporaryOptional.get();
        String v = villageCadresAddTemporary.getStatue();
        BeanUtils.copyProperties(villageCadresAddTemporaryDTO, villageCadresAddTemporary);
        if ("2".equals(villageCadresAddTemporaryDTO.getStatue()) && "1".equals(v)){
            VillageCadres villageCadres = new VillageCadres();
            villageCadres.setName(villageCadresAddTemporary.getName());
            villageCadres.setState("0");
            villageCadres.setHasRetire("0");
            villageCadres.setCadresType("IN_SECRETARY");
            villageCadres.setHeadSculpture("http://122.97.218.162:8888/g1/M00/00/B2/rBAAx151x-6AbVcSAAAJJXxlLy0086.png");
            villageCadres.setDistrictId(villageCadresAddTemporary.getDistrictId());
            villageCadres.setDistrictName(villageCadresAddTemporary.getDistrictName());
            villageCadres.setParentDistrictId(villageCadresAddTemporary.getParentDistrictId());
            villageCadres.setParentDistrictName(villageCadresAddTemporary.getParentDistrictName());
            villageCadres.setCadresPost(villageCadresAddTemporary.getCadresPost());
            villageCadres = villageCadresService.save(villageCadres);
            villageCadresAddTemporary.setCadresId(villageCadres.getId());
        }
        villageCadresAddTemporary.setStatue(villageCadresAddTemporaryDTO.getStatue());
        villageCadresAddTemporary = villageCadresAddTemporaryService.save(villageCadresAddTemporary);

        return Result.ofUpdateSuccess(villageCadresAddTemporary.convert(VillageCadresAddTemporaryVO.class));
    }

    @Override
    public Result delete(@ApiParam(value = "村干部临时表id", required = true) @PathVariable String id) {
        villageCadresAddTemporaryService.deleteById(id);
        return Result.ofDeleteSuccess();
    }

    @Override
    public Result<List<VillageCadresAddTemporaryVO>> list(@ApiParam(value = "村干部临时表查询条件", required = true) @RequestBody VillageCadresAddTemporarySearchable villageCadresAddTemporarySearchable,
        @ApiParam(value = "排序条件", required = true) Sort sort) {

        List<VillageCadresAddTemporary> villageCadresAddTemporaryList = villageCadresAddTemporaryService.findAll(villageCadresAddTemporarySearchable);
        List<VillageCadresAddTemporaryVO> villageCadresAddTemporaryVOList = VillageCadresAddTemporary.convert(villageCadresAddTemporaryList, VillageCadresAddTemporaryVO.class);
        return Result.of(villageCadresAddTemporaryVOList);
    }

    @Override
    public Result<Page<VillageCadresAddTemporaryVO>> page(@ApiParam(value = "村干部临时表查询条件", required = true) @RequestBody VillageCadresAddTemporarySearchable villageCadresAddTemporarySearchable,
        @ApiParam(value = "分页参数", required = true) Pageable pageable) {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(VillageCadresAddTemporary.class);
        if(villageCadresAddTemporarySearchable.getDistrictId() != null && villageCadresAddTemporarySearchable.getDistrictId().length() == 4){
            //镇
            detachedCriteria.add(Restrictions.eq("parentDistrictId",villageCadresAddTemporarySearchable.getDistrictId()));
            detachedCriteria.add(Restrictions.sqlRestriction("( statue = '0' or statue = '3' )"));
        }else if (villageCadresAddTemporarySearchable.getDistrictId() != null && villageCadresAddTemporarySearchable.getDistrictId().length() == 6){
            detachedCriteria.add(Restrictions.eq("districtId",villageCadresAddTemporarySearchable.getDistrictId()));
        }else {
            detachedCriteria.add(Restrictions.sqlRestriction("( statue = '1' or statue = '4' )"));
        }
        Integer total = villageCadresAddTemporaryService.getTotalCount(detachedCriteria);
        detachedCriteria.addOrder(Order.desc("createdAt"));
        Page<VillageCadresAddTemporary> villageCadresAddTemporaryPage = villageCadresAddTemporaryService.findAll(detachedCriteria,pageable,total);
        Page<VillageCadresAddTemporaryVO> villageCadresAddTemporaryVOPage = VillageCadresAddTemporary.convert(villageCadresAddTemporaryPage, VillageCadresAddTemporaryVO.class);
        return Result.of(villageCadresAddTemporaryVOPage);
    }

}
